package com.sx.pipeline.ui.task.participate.frag

import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.annotation.NonNull
import androidx.recyclerview.widget.LinearLayoutManager
import com.lxj.xpopup.XPopup
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.sx.mvvmlibs.bus.RxBus
import com.sx.mvvmlibs.utils.Logs
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYDataBindingBaseFragment
import com.sx.pipeline.app.config.IntentKey
import com.sx.pipeline.app.event.RefreshEvent
import com.sx.pipeline.app.event.TypeEvent
import com.sx.pipeline.arouth.RouteManager
import com.sx.pipeline.databinding.FragParticipateTaskBinding
import com.sx.pipeline.repos.http.res.MessageListVo
import com.sx.pipeline.repos.http.res.ReleaseTaskVo
import com.sx.pipeline.repos.http.res.RongGroupVO
import com.sx.pipeline.ui.task.approve.frag.ApproveTaskFragment
import com.sx.pipeline.ui.task.participate.ParticipateTaskVM
import io.reactivex.rxjava3.schedulers.Schedulers
import io.rong.imkit.RongIM


/**
 * @Author: YY
 * @Date: 2022/4/13
 * @Description: 我参与的任务列表
 */
class ParticipateTaskFragment :
    CYDataBindingBaseFragment<FragParticipateTaskBinding, ParticipateTaskVM>(R.layout.frag_participate_task) {
    private lateinit var mAdapter: ParticipateTaskListAdapter
    private var status = 0 //任务状态

    companion object {
        fun newInstance(position: Int) =
            ParticipateTaskFragment().apply {
                arguments = Bundle().apply {
                    putInt(IntentKey.ID, position)
                }
            }
    }

    override fun initData() {
        status = arguments?.getInt(IntentKey.ID)!!
        mViewModel.page = 1
        mViewModel.takePartTaskList(status)
        mViewModel.getRongGroupList()
        RxBus.getDefault().toObservable(RefreshEvent::class.java)
            .subscribeOn(Schedulers.io())
            .subscribe {
                mViewModel.page = 1
                mViewModel.takePartTaskList(status)
            }
    }

    private fun initRv() {
        if (!this::mAdapter.isInitialized) {
            mAdapter = ParticipateTaskListAdapter()
            mBinding.recyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            mBinding.recyclerView.adapter = mAdapter
        }
        mAdapter.setOnItemClickListener { adapter, view, position ->
            var info = adapter.data[position] as ReleaseTaskVo
            RouteManager.Mine.intentToParticipateTaskDetail(info.id)
        }
        //删除任务
        mAdapter.deleteTaskCallback = {
            XPopup.Builder(context)
                .isDestroyOnDismiss(true)
                .asConfirm(
                    getString(R.string.hint), getString(R.string.txt_delete_task_tips),
                    getString(R.string.cancel), getString(R.string.confirm),
                    {
                        //删除任务
                        mViewModel.getRemoveTask(it)
                    }, null, false
                ).show()
        }
        //加入群聊
        mAdapter.joinGroupCallback = { id: Int, groupId: String ->
            XPopup.Builder(context)
                .isDestroyOnDismiss(true)
                .asConfirm(
                    getString(R.string.hint), getString(R.string.txt_join_group_tips),
                    getString(R.string.cancel), getString(R.string.confirm),
                    {
                        //加入群聊
                        mViewModel.requestJoinGroup(id, groupId)
                    }, null, false
                ).show()
        }
    }

    override fun initViewObservable() {
        super.initViewObservable()
        mViewModel.participateTaskListEvent.observe(this) {
            val taskList = it as List<ReleaseTaskVo>
            initRv()
            if (mViewModel.page == 1) {
                if (taskList.isNotEmpty()) {
                    mAdapter?.data = taskList as MutableList<ReleaseTaskVo>
                    mBinding.recyclerView.visibility = View.VISIBLE
                    mBinding.emptyView.visibility = View.GONE
                } else {
                    mBinding.recyclerView.visibility = View.GONE
                    mBinding.emptyView.visibility = View.VISIBLE
                }
                mBinding.refreshLayout.finishRefresh()
            } else {
                if (taskList.isNotEmpty()) {
                    mAdapter?.addData(taskList)
                    mBinding.refreshLayout.finishLoadMore()
                } else {
                    mBinding.refreshLayout.finishLoadMoreWithNoMoreData()
                }
            }
        }

        //群聊创建成功
        observe(mViewModel.groupListEvent) {
            if (it != null) {
                refreshRongGroupInfo(it)
            }
        }


    }


    override fun initListener() {
        super.initListener()
        mBinding?.refreshLayout?.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(@NonNull refreshLayout: RefreshLayout) {
                mViewModel.page += 1
                mViewModel.takePartTaskList(status)
            }

            override fun onRefresh(@NonNull refreshLayout: RefreshLayout) {
                mViewModel.page = 1
                mViewModel.takePartTaskList(status)
            }
        })
    }

    private fun ApproveTaskFragment.refreshRongGroupInfo(friendList: List<RongGroupVO>) {
        //融云IM -> 刷新群组信息
        for (i in friendList.indices) {
            //后台拿到的联系人列表id 比对 融云id相同则缓存
            val group = io.rong.imlib.model.Group(
                friendList[i].id,
                friendList[i].name,
                Uri.parse("")
            )

            //通过网络请求动态加载群信息
            RongIM.getInstance().refreshGroupInfoCache(group)
            Logs.d("re缓存群聊信息成功：" + group)
        }
    }

    private fun refreshRongGroupInfo(friendList: List<RongGroupVO>) {
        //融云IM -> 刷新群组信息
        for (i in friendList.indices) {
            //后台拿到的联系人列表id 比对 融云id相同则缓存
            val group = io.rong.imlib.model.Group(
                friendList[i].id,
                friendList[i].name,
                Uri.parse("")
            )

            //通过网络请求动态加载群信息
            RongIM.getInstance().refreshGroupInfoCache(group)
            Logs.d("re缓存群聊信息成功：" + group)
        }
    }
}